package com.dekun.workhard.config.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dekun.workhard.config.security.CustomerUserDetail;
import com.dekun.workhard.entity.SysMenu;
import com.dekun.workhard.entity.SysUser;
import com.dekun.workhard.service.ISysMenuService;
import com.dekun.workhard.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Objects;

/**
 * 用户名密码登录
 */
@Component
public class UsernamePasswordDetailService implements UserDetailsService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Assert.hasLength(s, "输入账号不能为空!");

        SysUser user = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getLoginName, s));

        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在!");
        }

        List<SysMenu> menus = menuService.getListByLoginName(user.getLoginName());

        return new CustomerUserDetail(user, menus);
    }

}
